package com.example.sqlexample;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
	ListView mList;
	DatabaseHelper mDbHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mList = (ListView) findViewById(R.id.list);

		// Instantiate the database
		mDbHelper = new DatabaseHelper(this);

		// Show the notes
		updateList();
	}

	/**
	 * Gets the notes from the SQLite database and displays them in the ListView
	 */
	public void updateList() {
		// Get an ArrayList of the notes
		ArrayList<String> noteList = mDbHelper.generateNoteList();
		// Generate an ArrayAdapter with the notes
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, noteList);
		// Set the ListView's adapter
		mList.setAdapter(adapter);
	}

	public void addNoteDialog() {
		// New note dialog
		AlertDialog diag = new AlertDialog.Builder(this).create();
		diag.setTitle(getString(R.string.add_title));

		// Edit Text to allow text input
		final EditText noteInput = new EditText(this);
		noteInput.setHint(getString(R.string.note));

		// Set the dialog view to show the EditText
		diag.setView(noteInput);

		diag.setButton(DialogInterface.BUTTON_NEGATIVE,
				getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// Do nothing on "Cancel" press,
						// The dialog will automatically close
					}
				});

		diag.setButton(DialogInterface.BUTTON_POSITIVE,
				getString(R.string.add), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// Create a note with the text
						String text = noteInput.getText().toString();
						// Check to make sure the user entered text
						if (!text.isEmpty()) {
							mDbHelper.addNote(text);
							updateList();
						}
					}
				});

		diag.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add:
			// Add note option
			addNoteDialog();
			break;
		case R.id.action_delete:
			// Delete table action
			mDbHelper.delete();
			// After deleting and recreating
			// the table, update the ListView
			// to show the changes
			updateList();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

}
